package com.yykj.template.server.util;

import com.yykj.common.enums.ResultEnums;
import com.yykj.common.exception.NormalException;
import sun.font.FontDesignMetrics;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 *
 * Created by chendg on 2020/6/30 0030.
 */
public class ImageTool {


    private static void drawArcFont4Circle(Graphics2D g2d, int circleRadius, Font font,String context, boolean isTop) {

        if (font == null) {
            return;
        }

        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);

        //1.字体长度
        int fontTextLen = context.length();

        //2.字体大小，默认根据字体长度动态设定 TODO
        int fontSize = font.getSize();

        //3.字体样式
        int fontStyle = font.isBold() ? Font.BOLD : Font.PLAIN;

        //4.构造字体
//        Font f = new Font(font.getFontFamily(), fontStyle, fontSize);

        FontRenderContext context1 = g2d.getFontRenderContext();
        Rectangle2D rectangle = font.getStringBounds(context, context1);

        //5.文字之间间距，默认动态调整
        double fontSpace;
        if (fontTextLen == 1) {
            fontSpace = 0;
        } else {
            fontSpace = rectangle.getWidth() / (fontTextLen - 1) * 0.9;
        }

        //6.距离外圈距离
        int marginSize = 10;

        //7.写字
        double newRadius = circleRadius + rectangle.getY() - marginSize;
        double radianPerInterval = 2 * Math.asin(fontSpace / (2 * newRadius));

        double fix = 0.04;
        if (isTop) {
            fix = 0.18;
        }
        double firstAngle;
        if (!isTop) {
            if (fontTextLen % 2 == 1) {
                firstAngle = Math.PI + Math.PI / 2 - (fontTextLen - 1) * radianPerInterval / 2.0 - fix;
            } else {
                firstAngle = Math.PI + Math.PI / 2 - ((fontTextLen / 2.0 - 0.5) * radianPerInterval) - fix;
            }
        } else {
            if (fontTextLen % 2 == 1) {
                firstAngle = (fontTextLen - 1) * radianPerInterval / 2.0 + Math.PI / 2 + fix;
            } else {
                firstAngle = (fontTextLen / 2.0 - 0.5) * radianPerInterval + Math.PI / 2 + fix;
            }
        }

        for (int i = 0; i < fontTextLen; i++) {
            double theta;
            double thetaX;
            double thetaY;

            if (!isTop) {
                theta = firstAngle + i * radianPerInterval;
                thetaX = newRadius * Math.sin(Math.PI / 2 - theta);
                thetaY = newRadius * Math.cos(theta - Math.PI / 2);
            } else {
                theta = firstAngle - i * radianPerInterval;
                thetaX = newRadius * Math.sin(Math.PI / 2 - theta);
                thetaY = newRadius * Math.cos(theta - Math.PI / 2);
            }

            AffineTransform transform;
            if (!isTop) {
                transform = AffineTransform.getRotateInstance(Math.PI + Math.PI / 2 - theta);
            } else {
                transform = AffineTransform.getRotateInstance(Math.PI / 2 - theta + Math.toRadians(8));
            }
            Font f2 = font.deriveFont(transform);
            g2d.setFont(f2);
            g2d.drawString(context.substring(i, i + 1), (float) (circleRadius + thetaX + 40),
                    (float) (circleRadius - thetaY + 40));
        }
    }


    public static BufferedImage buildHospitalSign(String hospitalName,String saveName,String initCircleClePath){
        try {
            hospitalName = " " + hospitalName;
            FileInputStream fileInputStream = new FileInputStream(initCircleClePath);

            BufferedImage srcImage = ImageIO.read(fileInputStream);
            BufferedImage signImage = new BufferedImage(210,210 ,srcImage.getType());

            Graphics2D g = signImage.createGraphics();
            g.drawImage(srcImage, 0, 0, 210, 210, null);

            BufferedImage wordsPic = ImageTool.startGraphics2D(hospitalName);
            g.drawImage(wordsPic.getScaledInstance(200,200, Image.SCALE_AREA_AVERAGING),5,5,200,200,null);
            ImageIO.write(signImage, "png", new FileOutputStream(saveName));
            return signImage;
        } catch (IOException e) {
            e.printStackTrace();
            throw new NormalException(ResultEnums.PARAM_ERROR,e.getMessage());
        }
    }

    public static void main(String[] args) {
        buildHospitalSign("江苏省互联网医院","D:\\workspace\\yanglao\\test.png","D:\\workspace\\yanglao\\temp\\initCircle.png");
    }

    //图片宽度
    private static final int WIDTH = 200;
    //图片高度
    private static final int HEIGHT = 200;

    private static String message = " 朗森特专家医院";
    private static String centerName = "";

    public static BufferedImage startGraphics2D(String message1){
        // 定义图像buffer：高度，宽度，半透明
        BufferedImage buffImg = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
        //绘图
        Graphics2D g = buffImg.createGraphics();
        g.setColor(Color.RED);
        //线条的宽度
        g.setStroke(new BasicStroke(5));
        //设置锯齿圆滑
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        //绘制圆
        //周半径
        int radius = HEIGHT/2;
        //画图所出位置
        int CENTERX = WIDTH/2;
        //画图所处位置
        int CENTERY = HEIGHT/2;

//        //画圆
//        Ellipse2D circle = new Ellipse2D.Double();
//        circle.setFrameFromCenter(CENTERX, CENTERY, CENTERX + radius, CENTERY + radius);
//        g.draw(circle);
//
//        //绘制中间的五角星
//        g.setFont(new Font("宋体", Font.BOLD, 80));
//        g.drawString("★", CENTERX-(80/2), CENTERY+(80/3));
//
//        //写入签名
//        g.setFont(new Font("宋体", Font.BOLD, 20));// 写入签名
//        g.drawString(centerName, CENTERX -(47), CENTERY +(30+50));


        //根据输入字符串得到字符数组
        String[] messages2 = message1.split("",0);
        String[] messages = new String[messages2.length-1];
        System.arraycopy(messages2,1,messages,0,messages2.length-1);

        //输入的字数
        int ilength = messages.length;

        //设置message字体属性
        int fontsize = 35;

        int trueLength = message1.trim().length();
        if ( trueLength > 10 && trueLength <20){
            float pf = 2.0f - (trueLength-10 ) * 0.1f;
            //TODO 待修改的自适应逻辑
            fontsize = (int) (fontsize -(trueLength-10 ) *pf);
        }else if (trueLength >= 20 && trueLength < 30){
            fontsize = (int) (fontsize -(trueLength-10 ) *1.1f);
        }else if (trueLength >= 30){
           throw new NormalException(ResultEnums.PARAM_ERROR,"字数过长");
        }

        Font f = new Font("PingFang SC Medium", Font.BOLD, fontsize);


        //正确测量文本所需的信息容器
        FontRenderContext context = g.getFontRenderContext();
        //规定的位置(X,Y)和尺寸(宽x高)定义的字体
        Rectangle2D bounds = f.getStringBounds(message1, context);

        //字符宽度＝字符串长度/字符数
        double char_interval = (bounds.getWidth() / ilength);
        //上坡度
        double ascent = -bounds.getY();

        int first = 0,second = 0;
        boolean odd = false;
        if (ilength%2 == 1)
        {
            first = (ilength-1)/2;
            odd = true;
        }
        else
        {
            first = (ilength)/2-1;
            second = (ilength)/2;
            odd = false;
        }

        double radius2 = radius - ascent;
        double x0 = CENTERX;
        double y0 = CENTERY - radius + ascent;
        //旋转角度
        double a = 2*Math.asin(char_interval/(2*radius2));

        if (odd)
        {
            g.setFont(f);
            g.drawString(messages[first], (float)(x0 - char_interval/2), (float)y0);

            //中心点的右边打印
            for (int i=first+1;i<ilength;i++)
            {
                double aa = (i - first) * a;
                double ax = radius2 * Math.sin(aa);
                double ay = radius2 - radius2 * Math.cos(aa);
                AffineTransform transform = AffineTransform.getRotateInstance(aa);
                Font f2 = f.deriveFont(transform);
                g.setFont(f2);
                g.drawString(messages[i], (float)(x0 + ax - char_interval/2* Math.cos(aa)), (float)(y0 + ay - char_interval/2* Math.sin(aa)));
            }
            //中心点的左边打印
            for (int i=first-1;i>-1;i--)
            {
                double aa = (first - i) * a;
                double ax = radius2 * Math.sin(aa);
                double ay = radius2 - radius2 * Math.cos(aa);
                AffineTransform transform = AffineTransform.getRotateInstance(-aa);
                Font f2 = f.deriveFont(transform);
                g.setFont(f2);
                g.drawString(messages[i], (float)(x0 - ax - char_interval/2* Math.cos(aa)), (float)(y0 + ay + char_interval/2* Math.sin(aa)));
            }

        }
        else
        {
            //中心点的右边打印
            for (int i=second;i<ilength;i++)
            {
                double aa = (i - second + 0.5) * a;
                double ax = radius2 * Math.sin(aa);
                double ay = radius2 - radius2 * Math.cos(aa);
                AffineTransform transform = AffineTransform.getRotateInstance(aa);
                Font f2 = f.deriveFont(transform);
                g.setFont(f2);
                g.drawString(messages[i], (float)(x0 + ax - char_interval/2* Math.cos(aa)), (float)(y0 + ay - char_interval/2* Math.sin(aa)));
            }

            //中心点的左边打印
            for (int i=first;i>-1;i--)
            {
                double aa = (first - i + 0.5) * a;
                double ax = radius2 * Math.sin(aa);
                double ay = radius2 - radius2 * Math.cos(aa);
                AffineTransform transform = AffineTransform.getRotateInstance(-aa);
                Font f2 = f.deriveFont(transform);
                g.setFont(f2);
                g.drawString(messages[i], (float)(x0 - ax - char_interval/2* Math.cos(aa)), (float)(y0 + ay + char_interval/2* Math.sin(aa)));
            }
        }

        return buffImg;
    }
}
